package day_2022_9_to_12.Day;

/**
 * @author haomin
 * @date 2022/10/11 16:23
 **/
public class Day39_1_Num_AreAlmostEqual {
    class Solution {
        public boolean areAlmostEqual(String s1, String s2) {
            if(s1.length() != s2.length()) return false;
            if(s1.equals(s2)) return true;
            int[] ind = new int[]{-1, -1};
            for(int i = 0; i < s1.length(); ++i){
                if(s1.charAt(i) != s2.charAt(i)){
                    if(ind[0] == -1) ind[0] = i;
                    else if(ind[1] == -1) ind[1] = i;
                    else return false;
                }
            }
            if(ind[0] == -1) return true;
            if(ind[1] == -1) return false;
            char[] arr = s2.toCharArray();
            swap(arr, ind[0], ind[1]);
            return s1.equals(new String(arr));
        }
        private void swap(char[] arr, int i, int j){
            char temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }

    // 简化
    class Solution2 {
        public boolean areAlmostEqual(String s1, String s2) {
            if(s1.length() != s2.length()) return false;
            int[] ind = new int[]{-1, -1};
            for(int i = 0; i < s1.length(); ++i){
                if(s1.charAt(i) != s2.charAt(i)){
                    if(ind[0] == -1) ind[0] = i;
                    else if(ind[1] == -1) ind[1] = i;
                    else return false;
                }
            }
            if(ind[0] == -1) return true;
            if(ind[1] == -1) return false;
            return s1.charAt(ind[0]) == s2.charAt(ind[1]) && s1.charAt(ind[1]) == s2.charAt(ind[0]);
        }
    }
}